package com.ruoyi.quartz.task;

import com.ruoyi.agent.domain.KwMachineAgent;
import com.ruoyi.agent.service.IKwMachineAgentService;
import com.ruoyi.common.constant.HostConstant;
import com.ruoyi.common.utils.agent.AgentRestUtil;
import com.ruoyi.common.utils.pushgateway.PushGatewayUtils;
import com.ruoyi.machine.domain.KwMachineInfo;
import com.ruoyi.machine.service.IKwMachineInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 机器指标获取任务
 * 
 * @author gonianer
 */
@Component("hostMetricsTask")
public class HostMetricsTask
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IKwMachineInfoService machineInfoService;
    @Autowired
    private IKwMachineAgentService agentService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    public void pullHostMetrics()
    {
        try {
            //获取机器列表
            List<KwMachineInfo> machines = machineInfoService.selectKwMachineInfoList(new KwMachineInfo());
            //遍历机器列表，获取机器指标
            List<CompletableFuture> futures = new ArrayList<>();
            machines.stream().forEach(machine ->{
                if(HostConstant.STATUS_SUBMIT.equals(machine.getStatus())
                    || HostConstant.STATUS_DELETED.equals(machine.getStatus())){
                    CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
                        //执行指标获取步骤
                        logger.info("开始获取机器："+machine.getIp()+"，机器指标");
                        KwMachineAgent agent = new KwMachineAgent();
                        agent.setMachineId(machine.getId());
                        agent = agentService.selectKwMachineAgentList(agent).stream().findFirst().get();
                        if(agent==null){
                            logger.warn("获取机器："+machine.getIp()+"代理信息为空，无法获取指标");
                            return "failed";
                        }
                        //通过HTTP GET 访问代理获取机器指标
                        String metrics = AgentRestUtil.getHostMetrics(machine.getIp(),agent.getPort(),
                                agent.getHttpUser(),agent.getHttpPasswd());
                        //将指标数据push到pushgateway
                        PushGatewayUtils.push(machine.getIp(),metrics);
                        return "success";
                    },threadPoolTaskExecutor).handle((x,t)->{
                        logger.error(t.getMessage());
                        return "failed";
                    });
                    futures.add(future);
                }
            });
            CompletableFuture<Void> all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
            all.join();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
